package com.trdcore.zyzkt.controller;

import com.alibaba.fastjson2.JSONObject;
import com.trdcore.zyzkt.resp.ResultData;
import com.trdcore.zyzkt.service.MessageService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import org.apache.commons.codec.digest.DigestUtils;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/api/wechat/message")
public class MessageController {

    @Autowired
    private MessageService messageService;

    private static final String Token = "zyzkt";

    /**
     * 验证服务器地址的有效性
     */


    @GetMapping()
    public String checkSignature(@RequestParam(value = "signature") String signature,
                                 @RequestParam(value = "timestamp") String timestamp,
                                 @RequestParam(value = "nonce") String nonce,
                                 @RequestParam(value = "echostr") String echostr){

        String[] params = new String[]{nonce,timestamp,Token};
        Arrays.sort(params);
        String signatureResult = DigestUtils.sha1Hex(params[0]+params[1] + params[2]);
        //校验签名
        if(!signatureResult.equals(signature)) {
            throw new RuntimeException("signature is not the same wechat signature is " + signature + " signatureResult is " + signatureResult);
        }
        return echostr;

    }

    /**
     * 接收微信服务器发送来的消息
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping
    public String receiveMessage(HttpServletRequest request) throws Exception {
        Map<String, String> param = this.parseXml(request);
        return messageService.receiveMessage(param);
    }

    private Map<String, String> parseXml(HttpServletRequest request) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        InputStream inputStream = request.getInputStream();
        SAXReader reader = new SAXReader();
        Document document = reader.read(inputStream);
        Element root = document.getRootElement();
        List<Element> elementList = root.elements();
        for (Element e : elementList) {
            map.put(e.getName(), e.getText());
        }
        inputStream.close();
        inputStream = null;
        return map;
    }

    @GetMapping("/pushPayMessage")
    public ResultData pushPayMessage() throws WxErrorException {
        messageService.pushPayMessage(1L);
        return ResultData.success(null);
    }
}